package band.wukong.practice.javase.core.io.stream;

import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;

/**
 * Desc:
 * Author: sunjs
 * Date: 2009-11-13 14:33:31
 */
public class TestPipedStream {

    static class Sender extends Thread {
        private PipedOutputStream out;

        public Sender(PipedOutputStream out) {
            super();
            this.out = out;
        }

        public void run() {
            try {
                for (int i = -127; i <= 128; i++) {
                    out.write(i);
                    yield();
                }
                out.close();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        public PipedOutputStream getPipedOutputStream() {
            return out;
        }
    }

    static class Receiver extends Thread {
        private PipedInputStream in;

        public Receiver(Sender sender) throws IOException {
            super();
            in = new PipedInputStream(sender.getPipedOutputStream());
        }

        public void run() {
            try {
                int data;
                while ((data = in.read()) != -1) {
                    System.out.println("data = " + data);
                }
                in.close();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }

    public static void main(String[] args) throws Exception {
        Sender sender = new Sender(new PipedOutputStream());
        Receiver receiver = new Receiver(sender);
        sender.start();
        receiver.start();
        //TODO [Learn]线程处理的过程需要仔细看一下。
    }
}

